<template>
    <div id="login_container" class="wechat-login" style="text-align: center; margin-top: 100px;">
      <h2>请扫描下面的二维码登录</h2>
      <img :src="qrcodeImage.imageURL" alt="微信二维码" style="width: 200px; height: 200px;">
      <p>扫描二维码以完成登录</p>
    </div>
  </template>
  
<script lang="ts" setup>
import { onMounted, ref, watch } from 'vue'
import {useLayoutStore} from '@/store/modules/layout'
import {heartbeat} from "@/api/user"
import { showElMessage } from '@/utils/tools'
import router from '@/router'

const layoutStore = useLayoutStore()


const qrcodeImage = ref({
    ticket: "",
    imageURL: "",
    image: "",
})

onMounted(() => {
    qrcodeImage.value = layoutStore.qrcode

    if (qrcodeImage.value.imageURL === "") {
        layoutStore.getQrcodeImage()
            .then((res) => {
                qrcodeImage.value.imageURL = res.image_url
                qrcodeImage.value.ticket = res.ticket
            }).catch(() => {})
    }
})

// 建立长轮询，检查登录状态
var intervalId = setInterval(() => {
    heartbeat({ticket: qrcodeImage.value.ticket})
        .then((res) => {
            if (res.data && res.data.status === true) {
                showElMessage(res, 'success')
                localStorage.setItem("access_token", res.data.access_token)
                localStorage.setItem("refresh_token", res.data.refresh_token)
                layoutStore.status.accessToken = res.data.access_token
                layoutStore.status.refreshToken = res.data.refresh_token
                router.push(layoutStore.lastRoute || '/home')
                clearInterval(intervalId)
            }
        })
        .catch(() => {})
}, 1500)

setTimeout(() => {
    clearInterval(intervalId)
}, 30 * 1000)

</script>

<style scoped>
.wechat-login {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
}
</style>
